package com.example.yuejian2.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.MenuItem;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.yuejian2.R;
import com.example.yuejian2.adapter.MyPagerAdapter;
import com.example.yuejian2.bean.BannerEntity;
import com.example.yuejian2.common.GlideImageLoader;
import com.example.yuejian2.common.Url;
import com.example.yuejian2.fragment.MainFragment;
import com.example.yuejian2.view.DecoratorViewPager;
import com.lapism.searchview.Search;
import com.lapism.searchview.widget.SearchView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {

    private static final String TAG = "MainActivity";
    @BindView(R.id.vp)
    DecoratorViewPager viewpager;
    @BindView(R.id.search_view)
    SearchView searchView;
    @BindView(R.id.tablayout)
    TabLayout tabLayout;
    @BindView(R.id.banner)
    Banner banner;
    private Handler mhandler = new mHandler();
    private List<Fragment> fragmentList;
    private List<String> list_Title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
        initview();


    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.search_view:
                searchView.open(item);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void initview() {
        searchView.setOnOpenCloseListener(new Search.OnOpenCloseListener() {
            @Override
            public void onOpen() {
                ActivityUtils.startActivity(SearchActivity.class);
            }

            @Override
            public void onClose() {

            }
        });
        viewpager.setNestedpParent((ViewGroup) viewpager.getParent());
        fragmentList = new ArrayList<>();
        list_Title = new ArrayList<>();

        fragmentList.add(new MainFragment().setFlag("activity"));
        fragmentList.add(new MainFragment().setFlag("master"));
        fragmentList.add(new MainFragment().setFlag("bs"));

        list_Title.add("精彩活动");
        list_Title.add("权威大师");
        list_Title.add("最近比赛");

        viewpager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), this, fragmentList, list_Title));
        tabLayout.setupWithViewPager(viewpager);//此方法就是让tablayout和ViewPager联动

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用

        EasyHttp.get("yuejian6/public/index.php/json/banner/index")
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String data) {

                        Message msg = Message.obtain(); // 实例化消息对象
                        msg.what = 1; // 消息标识
                        msg.obj = data; // 消息内容存放

                        mhandler.sendMessage(msg);

                    }

                    @Override
                    public void onError(ApiException error) {
                        Log.d(TAG, "onFailed: " + error);
                    }
                });

    }

    @Override
    protected void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    @OnClick(R.id.train)
    void train() {

        ActivityUtils.startActivity(TrainActivity.class);

    }

    @OnClick(R.id.my)
    void my() {

        ActivityUtils.startActivity(MyActivity.class);

    }

    @OnClick(R.id.club)
    void club() {

        ActivityUtils.startActivity(ClubActivity.class);

    }

    @OnClick(R.id.st)
    void st() {
        ActivityUtils.startActivity(STActivity.class);

    }

    // 步骤1：自定义Handler子类（继承Handler类） & 复写handleMessage（）方法
    class mHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            Log.d(TAG, "handleMessage: " + msg.obj.toString());
            List<BannerEntity> banners = null;

            try {
                banners = JSON.parseArray(msg.obj.toString(), BannerEntity.class);
            } catch (Exception e) {
                ToastUtils.showShort("获取数据失败");
                return;
            }


            List<String> imgs = new ArrayList<>();
            List<String> titles = new ArrayList<>();

            for (BannerEntity banner : banners) {
                imgs.add(Url.imgUrl + banner.getPic());
                titles.add(banner.getIntro());
            }


            //设置标题集合（当banner样式有显示title时）
            banner.setBannerTitles(titles);
            //设置图片集合
            banner.setImages(imgs);
            banner.start();

        }
    }

}